/**
 * 用户相关服务
 */

const util = require('../utils/util.js');
const api = require('../config/api.js');
const wxcache = require('../utils/wxcache.js');



/**
 * 调用微信登录
 */
function loginByWeixin() {

  let code = null;
  return new Promise(function (resolve, reject) {
    return util.login().then((res) => {
      code = res.code;
      return util.getUserInfo();
    }).then((userInfo) => {
      //登录远程服务器
      util.request(api.AuthLoginByWeixin, { code: code, userInfo: userInfo }, 'POST').then(res => {
        if (res.errno === 0) {
          //存储用户信息
          wxcache.put('userInfo', res.data.userInfo);
          wxcache.put('token', res.data.token);

          resolve(res);
        } else {
          reject(res);
        }
      }).catch((err) => {
        reject(err);
      });
    }).catch((err) => {
      reject(err);
    })
  });
}

/**
 * 判断用户是否登录
 */
function checkLogin() {
  return new Promise(function (resolve, reject) {
    if (wxcache.get('token') && wxcache.get('phoneNumber') ) {

      util.checkSession().then(() => {
        resolve(true);
      }).catch(() => {
        reject(false);
      });
    } else {
      reject(false);
    }
    resolve(true);

  });
}

/**
 * 判断用户是否是新用户
 * 
 * 
*/
function checkNew() {
  return new Promise(function (resolve, reject) {

    let phone = wxcache.get('phoneNumber')
    util.request(api.IsNewPerson, { mobile: phone}).then(function (res) {

      console.log(res)
      if(res.responseBody == true){
        resolve(true);
      }else{
        reject(false);
      }
    }).catch(() => {
        reject(false);
      });
  });
}

/**
 * 判断用户是否设置过密码
*/
function checkSetPWD() {
  return new Promise(function (resolve, reject) {

    let phone = wxcache.get('phoneNumber')
    util.request(api.QueryUserInfo, { mobile: phone }).then(function (res) {

      console.log(res)
      if (res.responseBody.hasPassword) {
        resolve(true);
      }else{
        reject(false);
      }
    }).catch(() => {
      reject(false);
    });


  });
}

function getUserinfoByButton(e){

  return  new Promise(function (resolve, reject){

    var app = getApp();
      
      // 只有在第一点击button的时候，才会出现弹出
      console.log(e.detail.errMsg)
      console.log(e.detail.userInfo)
      console.log(e.detail.rawData)

      var wxusrinfo = e.detail.userInfo



      var phonenumber = wxcache.get("phoneNumber")

      if(phonenumber){
        util.request(api.QueryUserInfo, { mobile: phonenumber }).then(function (res) {

          if(res.code == 200){

            var userinfotmp = res.responseBody;

            //注册过,并且微信认证过
            if (userinfotmp.mobile && userinfotmp.openId) {
              console.log("注册过,并且微信认证过")
              wxcache.put("userInfo", res.responseBody)
              resolve(true);
            } else {

                console.log("未注册,未授权")
                //获取userinfo成功，放入缓存
                var data = {}
                data.encryptedData = e.detail.encryptedData
                data.iv = e.detail.iv
                data.thirdSessionId = wxcache.get('token');
           
                util.request(api.GetDecodeUserInfo, data, 'POST').then(function (res) {
                  wxcache.put("userInfo", res.responseBody)
                }).then(res=>{

                  var usertmp = wxcache.get("userInfo")
                  usertmp.mobile = wxcache.get("phoneNumber")
                  util.request(api.InitUserInfo, usertmp, 'POST').then(function (res) {
                    console.log(res)
                  }).then(res => {
                    util.request(api.QueryUserInfo, { mobile: wxcache.get("phoneNumber") })
                      .then(res => {
                        wxcache.put("userInfo", res.responseBody);
                      })
                  })
                })
              resolve(true);
            }
          }else{
            
            var data = {}
            data.encryptedData = e.detail.encryptedData
            data.iv = e.detail.iv
            data.thirdSessionId = wxcache.get('token');
            util.request(api.GetDecodeUserInfo, data, 'POST').then(function (res) {
              wxcache.put("userInfo", res.responseBody)
            })
            resolve(true);
          }
        })
      }else{
        var data = {}
        data.encryptedData = e.detail.encryptedData
        data.iv = e.detail.iv
        data.thirdSessionId = wxcache.get('token');
        util.request(api.GetDecodeUserInfo, data, 'POST').then(function (res) {
          wxcache.put("userInfo", res.responseBody)
        })
        resolve(true);
      }
  })
}




module.exports = {
  loginByWeixin,
  checkLogin,
  checkNew,
  checkSetPWD,
  getUserinfoByButton,
};











